<template>
  <el-dialog
    :model-value="visible"
    title="用户信息"
    width="800"
    :close-on-click-modal="false"
    @update:model-value="updateVisible"
    @close="cls"
  >
    <div>
      <div class="content">
        <el-form
          :model="localUser"
          style="max-width: 1200px; margin-top: 20px"
          label-width="150px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户ID:">
                <el-input
                  v-model="localUser.id"
                  autocomplete="off"
                  style="width: 300px"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号:">
                <el-input
                  v-model="localUser.mobile"
                  autocomplete="off"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名:">
                <el-input
                  v-model="localUser.name"
                  autocomplete="off"
                  style="width: 300px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色:">
                <el-select
                  v-model="localUser.role_name"
                  style="width: 300px"
                  @change="onRoleChange"
                >
                  <el-option
                    v-for="item in roles"
                    :key="item.id"
                    :label="item.rname"
                    :value="item.rname"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="性别:">
                <el-select
                  v-model="localUser.sex"
                  style="width: 300px"
                  @change="onSexChange"
                >
                  <el-option :label="'男'" :value="1" />
                  <el-option :label="'女'" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="dialog-footer">
      <el-button @click="cls">关闭</el-button>
      <el-button type="primary" @click="updateUse"> 提交 </el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import { getRole, updateUser } from "@/api/user/user.js";
import { ElMessage } from "element-plus";

// 接收父组件传递的props
const props = defineProps({
  visible: Boolean, // 控制对话框显示与否
  user: Object // 用户数据
});

// 触发父组件关闭事件
const emit = defineEmits(["close", "update:model-value"]);

// 本地用户信息
let localUser = ref({
  id: 0,
  name: "",
  mobile: "",
  role_id: 1,
  role_name: "", // 角色名称
  sex: 1
});

let roles = ref([]);

// 路由对象
let router = useRouter();

/**
 * 获取角色列表
 */
async function getRoles() {
  let res = await getRole();
  if (res.code == 200) {
    roles.value = res.data;
  }
}

/**
 * 提交修改
 */
async function updateUse() {
  let res = await updateUser(localUser.value);
  if (res.code == 200) {
    ElMessage.success("修改成功！");
    emit("close"); // 通知父组件关闭对话框
    emit("refreshUserList"); // 通知父组件刷新用户列表
    router.push({ path: "/user/userList" });
  } else {
    ElMessage.error("修改失败！");
  }
}

/**
 * 角色选择发生变化时的处理
 */
function onRoleChange(value) {
  const selectedRole = roles.value.find(role => role.rname === value);
  if (selectedRole) {
    localUser.value.role_id = selectedRole.id; // 根据角色名称更新role_id
  }
}
/**
 * 性别选择发生变化时的处理
 */
function onSexChange(value) {
  localUser.value.sex = value; // 更新localUser的sex
}
/**
 * 关闭对话框
 */
function cls() {
  localUser.value = {};
  emit("close"); // 通知父组件关闭对话框
}

/**
 * 更新对话框的显示状态
 */
function updateVisible(newVal) {
  emit("update:model-value", newVal);
}

// 监听 props.user 变化，确保同步数据
watch(
  () => props.user,
  newUser => {
    if (newUser) {
      localUser.value = { ...newUser }; // 同步 props.user 数据到 localUser
      localUser.value.role_id = Number(localUser.value.role_id); // 确保 role_id 是数字类型
      const role = roles.value.find(r => r.id === localUser.value.role_id);
      if (role) {
        localUser.value.role_name = role.rname; // 设置对应的角色名称
      }
      localUser.value.sex = Number(newUser.sex); // 确保性别是数字类型
    }
  },
  { immediate: true }
);

// 初始化加载角色列表
onBeforeMount(() => {
  getRoles();
});
</script>

<style scoped></style>
